/**
 * Created by lvlq on 16/2/26.
 */
var Q = require("q");
var sequelize = Util("sequelize");
var func = Util("Func.http");
var wxApi = Util("wx.api");
var fs = require("fs");
var saveDir = __dirname + "/../../Public/upload/";
var uuid = require("uuid");

var index = function (req, res) {
    res.render("index.html");
};

var lucky = function (req, res) {
    req.session.image_url = "";
    req.session.acCode = "";
    var UserList = M("index.userList");
    var uid = req.cookies.uid;

    UserList.find({
        where: {
            uid: uid,
            aid: 1
        }
    }).then(function (data) {
        if (data) {
            res.redirect("/index/shell/once");
        } else {
            res.render("lucky.html", {data: data, exist: 0});
        }
    });
};

var more = function (req, res) {
    res.render("more.html");
};

var share = function (req, res) {
    res.render("share.html");
};

var once = function (req, res) {
    res.render("once.html");
};

var fightdesc = function (req, res) {
    var UserList = M("index.userList");
    var uid = req.cookies.uid;

    UserList.find({
        where: {
            uid: uid,
            aid: 2
        }
    }).then(function (data) {
        if (data) {
            res.redirect("/index/shell/once");
        } else {
            res.render("fightdesc.html");
        }
    });
};

var fightupload = function (req, res) {
    var media_id = req.query.media_id;
    var local_id = req.query.local_id;
    req.session.media_id = media_id;
    req.session.local_id = local_id;
    res.render("fightupload.html", {local_id: local_id, media_id: media_id});
};

var fightqccode = function (req, res) {
    var media_id = req.query.media_id;
    req.session.media_id = media_id;

    res.render("fightqccode.html", {media_id: media_id});
};

var fightrolutte = function (req, res) {
    var UserList = M("index.userList");
    var uid = req.cookies.uid;

    UserList.find({
        where: {
            uid: uid,
            aid: 2
        }
    }).then(function (data) {
        if (data) {
            res.render("fightrolutte.html", {data: data, exist: 1});
        } else {
            res.render("fightrolutte.html", {data: data, exist: 0});
        }
    });

};

var fightshare = function (req, res) {
    res.render("fightshare.html");
};

var prize = function (req, res) {
    var aid = req.body.aid;
    var img_url = req.session.image_url;
    var acCode = req.session.acCode;
    var uid = req.cookies["uid"];
    var return_data = {};
    var UserList = M("index.userList");
    if (aid == 2 && img_url == "") {
        return res.json({errno: 10002, err: "未上传图片"});
    }

    if (!uid) {
        console.log("Error:非法");
        return res.json({errno: 10002, err: "非法"});
    }

    UserList.find({
        where: {
            uid: uid,
            aid: aid
        }
    }).then(function (data) {
        if (data) {
            throw new Error("已抽过奖");
        }
        return getPrize(aid);
    }).then(function (data) {
        return_data = data;
        return UserList.update({
            uid: uid,
            img_url: "http://shellrev.weixinzjit.com" + img_url,
            ac_code: acCode
        }, {
            where: {
                id: data.id
            }
        });
    }).then(function () {
        res.json({
            errno: 0,
            data: return_data
        });
    }).catch(function (err) {
        res.json({errno: 10002, err: err.message});
    })
};

var getPrize = function (aid) {
    var defer = Q.defer();
    var PrizeList = M("index.prizeList");

    PrizeList.findAll({
        where: {
            aid: aid,
            has_num: {
                gt: 0
            }
        }
    }).then(function (data) {
        var rand = Math.floor(Math.random() * 10000);
        var i;
        for (i = 0; i < data.length; i++) {
            rand -= parseInt(data[i].chance);
            if (rand < 0) {
                break;
            }
        }
        if (rand < 0) {
            return updatePrize(data[i].id);
        } else {
            defer.reject(new Error("没中奖"));
        }
    }).then(function (data) {
        defer.resolve(data);
    }).catch(function (err) {
        defer.reject(err);
    });

    return defer.promise;
};

var updatePrize = function (id) {
    var defer = Q.defer();
    var PrizeList = M("index.prizeList");
    var UserList = M("index.userList");
    sequelize.transaction(function (t) {
        return PrizeList.find({
            where: {
                id: id
            },
            lock: t.LOCK.UPDATE,
            transaction: t
        }).then(function (data) {
            if (data.has_num > 0 && data.chance > 0) {
                return PrizeList.update({
                    has_num: data.has_num - 1
                }, {
                    where: {
                        id: id
                    },
                    transaction: t
                }).then(function () {
                    return data;
                })
            } else {
                throw new Error("奖品发光了");
            }
        }).then(function (data) {
            return UserList.create({
                aid: data.aid,
                pid: id,
                pname: data.name
            })
        }).then(function (result) {
            t.commit();
            defer.resolve(result);
        }).catch(function (err) {
            t.rollback();
            defer.reject(err);
        });
    }).catch(function (err) {
        defer.reject(err);
    });

    return defer.promise;
};

var checkcode = function (req, res) {
    var ip = req.headers['x-real-ip'];
    var acCode = req.body.acCode;
    var media_id = req.body.media_id;
    var uid = req.cookies["uid"];
    console.log(media_id);
    var return_data = {};
    func.checkAcCode(ip, acCode)
        .then(function (data) {
            console.log(data.result.item[0]);
            console.log(data.result.item[0]["$"]);
            if (data.result.item[0].resultmsg[0] == "1" && data.result.item[0].matchflag[0] == "1") {
                //res.json({data: "ok"});
                return downloadImg(media_id)
            } else {
                throw new Error("验证未通过");
            }
        })
        .then(function (d) {
            req.session.image_url = d.path;
            req.session.acCode = acCode;
            var ImageList = M("index.imageList");
            return ImageList.create({
                uid: uid,
                url: "http://shellrev.weixinzjit.com" + d.path
            });
        }).then(function () {
            res.json({
                errno: 0
            });
        })
        .catch(function (err) {
            res.json({errno: 1001, err: err.message});
        })
};

var downloadImg = function (media_id) {
    var defer = Q.defer();
    wxApi.getMedia(media_id, function (err, buffer) {
        if (err)
            defer.reject(err);
        else {
            var filename = uuid.v1() + ".png";
            var filePath = saveDir + filename;
            var path = "/upload/" + filename;
            fs.writeFileSync(filePath, buffer);

            defer.resolve({
                filePath: filePath,
                path: path
            });
        }
    });
    return defer.promise;
};

var updateAddress = function (req, res) {
    var id = req.body.id;
    var name = req.body.name;
    var phone = req.body.phone;
    var address = req.body.address;

    var UserList = M("index.userList");
    UserList.update({
        name: name,
        phone: phone,
        address: address
    }, {
        where: {
            id: id
        }
    }).then(function () {
        res.json({errno: 0});
    }).catch(function () {
        res.json({errno: 10005, err: "插入失败"});
    })
};

module.exports = {
    index: index,
    lucky: lucky,
    share: share,
    once: once,
    more: more,
    fightdesc: fightdesc,
    fightupload: fightupload,
    fightqccode: fightqccode,
    fightrolutte: fightrolutte,
    fightshare: fightshare,
    prize: prize,
    checkcode: checkcode,
    updateAddress: updateAddress
};